package com.ruoyi.act.service.impl;

import com.ruoyi.act.domain.VO.DefinitionVO;
import com.ruoyi.act.service.ActProcessDefinitionService;
import com.ruoyi.common.core.domain.AjaxResult;
import org.activiti.engine.ProcessEngine;
import org.activiti.engine.ProcessEngines;
import org.activiti.engine.RepositoryService;
import org.activiti.engine.repository.Deployment;
import org.activiti.engine.repository.ProcessDefinition;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;

@Service
public class ActProcessDefinitionServiceImpl implements ActProcessDefinitionService {

    @Autowired
    private RepositoryService repositoryService;

    /**
     * 根据string部署流程
     */
    public AjaxResult initDeploymentBPMN(String name, String stringBPMN, String key){
        Deployment deployment = this.repositoryService.createDeployment()
                .addString(name, stringBPMN)
                .key(key)
                .name(name)
                .deploy();
        return AjaxResult.success();
    }

    /**
     * 删除部署流程
     */
    public AjaxResult delDeploymentBPMN(String id){
        //1，创建processEngine对象
        ProcessEngine processEngine = ProcessEngines.getDefaultProcessEngine();
        //2，得到RepositoryService对象
        RepositoryService repositoryService = processEngine.getRepositoryService();
        //3，执行删除流程定义，参数代表流程部署的id
        repositoryService.deleteDeployment(id);
        return AjaxResult.success();
    }

    /**
     * 获取所有最新版本的流程定义，按部署id排序
     * @return
     */
    public List<DefinitionVO> getDefinitions(){
        List<DefinitionVO> voList = new ArrayList<>();
        List<ProcessDefinition> list = this.repositoryService.createProcessDefinitionQuery()
                .latestVersion()
                .orderByDeploymentId().asc()
                .list();
        for (ProcessDefinition e : list){
            DefinitionVO vo = new DefinitionVO();
            vo.setId(e.getId());
            vo.setDeploymentId(e.getDeploymentId());
            vo.setName(e.getName());
            vo.setKey(e.getKey());
            vo.setVersion(e.getVersion());
            vo.setResourceName(e.getResourceName());
            vo.setDiagramResourceName(e.getDiagramResourceName());
            voList.add(vo);
        }
        return voList;
    }

    /**
     * 读取流程资源
     * 可以用于获取流程的图片和xml
     * @param processDefinitionId 流程定义ID
     * @param resourceName        资源名称
     */
    public InputStream readResource(String processDefinitionId, String resourceName){
        //通过流程部署id和资源名称获取流
        InputStream resourceAsStream = repositoryService.getResourceAsStream(processDefinitionId, resourceName);
        return resourceAsStream;
    }
}
